package net.mihome.app.ui;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.FileUtils;
import net.mihome.app.common.ImageUtils;
import net.mihome.app.common.StringUtils;
import net.mihome.app.common.UIHelper;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;
import net.mihome.app.widget.LoadingDialog;

import org.apache.http.Header;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class MifuwuBaoxiuNewActivity extends BaseActivity {
	private AppContext appContext;
    private User adminUser;
    private EditText typeTv;
    private EditText addressEt;
    private EditText contentEt;
    private LoadingDialog loadingDialog;
    private ImageView imageView;
    private String theLarge;
    private String theThumbnail;

    private final static int GROUP_AVATAR_CHOICE_SDCARD=101;  //从sd卡中取图片
    private final static int GROUP_AVATAR_CHOICE_CANMA=102;   //照相机
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mifuwu_wuye_baoxiu_new);
        typeTv= (EditText) findViewById(R.id.baoxiu_pub_type);
        addressEt= (EditText) findViewById(R.id.baoxiu_pub_address);
        contentEt= (EditText) findViewById(R.id.baoxiu_pub_content);
        imageView= (ImageView) findViewById(R.id.baoxiu_pub_img);
        adminUser= (User) getIntent().getSerializableExtra("admin_user");
        if(adminUser==null){
            initAdminUserInfo();
        }
        final String[] items=getResources().getStringArray(R.array.post_pub_options);
        typeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTypeDialog(MifuwuBaoxiuNewActivity.this,items,typeTv);
            }
        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CharSequence[] items = {
                        getString(R.string.img_from_album),
                        getString(R.string.img_from_camera)};
                imageChooseItem(items);
            }
        });
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	public void callWuye(View view){
        if(adminUser==null||adminUser.getMobile()==null||"".equals(adminUser.getMobile().trim())){
            Toast.makeText(this,"物业管理员信息无效,请于物业公司联系",Toast.LENGTH_SHORT).show();
            return;
        }
        String mobile=adminUser.getMobile().trim();
        if(adminUser.getCommunity()!=null&&adminUser.getCommunity().getBaoxiuMobile()!=null){
            mobile=adminUser.getCommunity().getBaoxiuMobile().trim();
        }
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mobile));
        startActivity(intent);
    }
    /**
     * 弹出单选框，选择报修类型
     * */
    /**
     * 单选Dialog
     */
    public void showTypeDialog(final Context mContext,final String[] items,final EditText typeEdit){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setIcon(R.drawable.baoxiu_mini_icon);
        builder.setTitle("请选择报修类型");
        builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                String phoneNum=items[which];
                typeEdit.setText(phoneNum);
            }
        });
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        builder.create().show();
    }
     /**
     * 发布保修信息
     * */
    public void pubBaoxiu(View view){
        if(loadingDialog==null){
            loadingDialog=new LoadingDialog(this);
        }
        loadingDialog.setTitle("正在报修..");
        loadingDialog.show();
        RequestParams requestParams=RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("content",typeTv.getText());
        requestParams.put("address",addressEt.getText());
        requestParams.put("mark",contentEt.getText());
        requestParams.put("imgs",(String)imageView.getTag());
        AppContext.ASYNC_HTTP_CLIENT.get(this,URLs.MIHOME_GET_REPAIR_ADD,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                loadingDialog.dismiss();
                finish();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                loadingDialog.dismiss();
                Toast.makeText(MifuwuBaoxiuNewActivity.this,"报修失败"+arg3.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }
    /**
     * 操作选择
     *
     * @param items
     */
    public void imageChooseItem(CharSequence[] items) {
        android.app.AlertDialog imageDialog = new android.app.AlertDialog.Builder(this)
                .setTitle(R.string.ui_insert_image)
                .setIcon(android.R.drawable.btn_star)
                .setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        // 手机选图
                        if (item == 0) {
                            Intent intent;
                            if (Build.VERSION.SDK_INT < 19) {
                                intent = new Intent();
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.setType("image/*");
                                startActivityForResult(
                                        Intent.createChooser(intent, "选择图片"),
                                        GROUP_AVATAR_CHOICE_SDCARD);
                            } else {
                                intent = new Intent(
                                        Intent.ACTION_PICK,
                                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                intent.setType("image/*");
                                startActivityForResult(
                                        Intent.createChooser(intent, "选择图片"),
                                        GROUP_AVATAR_CHOICE_SDCARD);
                            }
                        }
                        // 拍照
                        else if (item == 1) {
                            String savePath = "";
                            // 判断是否挂载了SD卡
                            String storageState = Environment
                                    .getExternalStorageState();
                            if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                                savePath = Environment
                                        .getExternalStorageDirectory()
                                        .getAbsolutePath()
                                        + "/OSChina/Camera/";// 存放照片的文件夹
                                File savedir = new File(savePath);
                                if (!savedir.exists()) {
                                    savedir.mkdirs();
                                }
                            }

                            // 没有挂载SD卡，无法保存文件
                            if (StringUtils.isEmpty(savePath)) {
                                UIHelper.ToastMessage(MifuwuBaoxiuNewActivity.this,
                                        "无法保存照片，请检查SD卡是否挂载");
                                return;
                            }

                            String timeStamp = new SimpleDateFormat(
                                    "yyyyMMddHHmmss").format(new Date());
                            String fileName = "osc_" + timeStamp + ".jpg";// 照片命名
                            File out = new File(savePath, fileName);
                            Uri uri = Uri.fromFile(out);

                            theLarge = savePath + fileName;// 该照片的绝对路径

                            Intent intent = new Intent(
                                    MediaStore.ACTION_IMAGE_CAPTURE);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startActivityForResult(intent,
                                    GROUP_AVATAR_CHOICE_CANMA);
                        }
                    }
                }).create();

        imageDialog.show();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

            switch (requestCode) {
                case GROUP_AVATAR_CHOICE_SDCARD:{
                    onActivityResult2(requestCode,resultCode,data);
                    break;
                }
                case GROUP_AVATAR_CHOICE_CANMA:{
                    onActivityResult2(requestCode,resultCode,data);
                    break;
                }
                default:
                    break;
            }
        }
    /**
     * 处理图片,onActivityResult方法是在太长了，分出来做
     */

    public void onActivityResult2(final int requestCode, final int resultCode, final Intent imageReturnIntent) {
        if(loadingDialog==null){
            loadingDialog = new LoadingDialog(this);
        }
        loadingDialog.setTitle("正在上传...");
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.show();
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                loadingDialog.dismiss();
                if (msg.what == 1 && msg.obj != null) {
                    // 显示图片
                    String imgUrl= (String) msg.obj+"?_id="+System.currentTimeMillis();
                    if(imgUrl!=null){
                        ImageLoader.getInstance().clearMemoryCache();
                        ImageLoader.getInstance().displayImage(imgUrl, imageView);
                        imageView.setTag(imgUrl);
                    }
                }else{
                    UIHelper.showAlertDialog(MifuwuBaoxiuNewActivity.this,"抱歉","图片上传失败");
                }
            }
        };
        new Thread(){
            private String selectedImagePath;
            @Override
            public void run() {
                Bitmap bitmap = null;
                if (requestCode == GROUP_AVATAR_CHOICE_SDCARD) {
                    if (imageReturnIntent == null)
                    {
                        return;
                    }
                    Uri selectedImageUri = imageReturnIntent.getData();
                    if (selectedImageUri != null) {
                        selectedImagePath = ImageUtils.getImagePath(selectedImageUri, MifuwuBaoxiuNewActivity.this);
                    }

                    if (selectedImagePath != null) {
                        theLarge = selectedImagePath;
                    } else {
                        bitmap = ImageUtils.loadPicasaImageFromGalley(selectedImageUri, MifuwuBaoxiuNewActivity.this);
                    }

                    if (AppContext.isMethodsCompat(android.os.Build.VERSION_CODES.ECLAIR_MR1)) {
                        String imaName = FileUtils.getFileName(theLarge);
                        if (imaName != null)
                            bitmap = ImageUtils.loadImgThumbnail(MifuwuBaoxiuNewActivity.this,
                                    imaName,
                                    MediaStore.Images.Thumbnails.MICRO_KIND);
                    }
                    if (bitmap == null && !StringUtils.isEmpty(theLarge))
                        bitmap = ImageUtils.loadImgThumbnail(theLarge, 100, 100);
                }else if (requestCode == GROUP_AVATAR_CHOICE_CANMA) {
                    if (bitmap == null && !StringUtils.isEmpty(theLarge)) {
                        bitmap = ImageUtils.loadImgThumbnail(theLarge, 100, 100);
                    }
                }
                if(bitmap!=null){
                    // 存放照片的文件夹
                    String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mihome/Camera/";
                    File savedir = new File(savePath);
                    if (!savedir.exists()) {
                        savedir.mkdirs();
                    }

                    String largeFileName = FileUtils.getFileName(theLarge);
                    String largeFilePath = savePath + largeFileName;
                    // 生成上传的800宽度图片
                    String thumbFileName = "thumb_" + largeFileName;
                    theThumbnail = savePath + thumbFileName;
                    Message msg = new Message();
                    try {
                        // 压缩上传的图片
                        File tFile=new File(theThumbnail);
                        if(tFile.exists()){
                            tFile.delete();
                            ImageLoader.getInstance().clearMemoryCache();
                        }
                        ImageUtils.createImageThumbnail(MifuwuBaoxiuNewActivity.this,theLarge, theThumbnail, 800, 80);
                        File imgFile = new File(theThumbnail);
                        String imageUrl=AppContext.getInstance().uploadImage(imgFile);
                        //imageFile可以作为上传
                        msg.what = 1;
                        msg.obj = imageUrl;
                        handler.sendMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                        msg.what = -1;
                        handler.sendMessage(msg);
                    }
                }
                super.run();
            }
        }.start();
    }
    /**
     * 初始化物业公司管理员信息
     * */
    public void initAdminUserInfo(){
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_USER_GET_COMMUNITY_ADMIN,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                adminUser=User.parse(responsePojo.getData());
            }
            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(MifuwuBaoxiuNewActivity.this, "请求物业管理员信息失败" + arg3.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
